package com.metadata_system.common.service;


import com.metadata_system.common.http.request_dto.LoginUserRequest;
import com.metadata_system.common.db.entity.AuthReflushToken;
import com.metadata_system.common.db.mapper.AuthReflushTokenMapper;
import com.metadata_system.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @author safi
 * @date 2019年10月9日20:30:57
 */
@Service
@Slf4j
public class AuthReflushTokenService {

    @Autowired
    AuthTokenService authTokenService;

    @Autowired(required = false)
    AuthReflushTokenMapper authReflushTokenMapper;

    @Autowired
    JwtUtil jwtUtil;


    // 检查刷新token是否有效

    public AuthReflushToken checkToken(LoginUserRequest loginUserRequest, String reflushTokenString) {
        // 2.Jwt 格式,有效期验证
        if (!this.jwtUtil.validateToken(reflushTokenString)) {
            log.warn("token 验证失败");
            return null;
        }
        // 3.获取 Jwt 数据
        Claims claims = this.jwtUtil.getClaimsFromToken(reflushTokenString);
        if (claims == null) {
            log.warn("token 解析失败");
            return null;
        }
        String claimsTokenId = claims.get("tokenId", String.class);
        String claimsUserType = claims.get("userType", String.class);
        String claimsUsername = claims.get("username", String.class);
        if(StringUtils.isEmpty(claimsTokenId) || claimsUserType==null || StringUtils.isEmpty(claimsUsername)){
            log.warn("token 数据提取失败");
            return null;
        }

        Example example = new Example(AuthReflushToken.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("reflushTokenId", claimsTokenId);
        criteria.andEqualTo("status", 1);

        // 5.可以换成 redis 读取
        AuthReflushToken authReflushToken = this.authReflushTokenMapper.selectByExampleAndRowBounds(example,new RowBounds(0,1)).get(0);
        if (authReflushToken==null) {
            log.warn("token 状态已经失效: {}",claimsTokenId);
            return null;
        }

        // 6.返回当前: reflushToken
        return AuthReflushToken.builder()
                // reflushTokenID
                .tokenId(claimsTokenId)
                .build();
    }
}
